import { Component, OnInit } from '@angular/core';
import { StaffDto } from 'src/app/shared/services/http/dto/staff.dto';
import { StaffsService } from 'src/app/shared/services/http/staffs.service';
import { CoreService } from 'src/app/shared/services/core.service';

@Component({
  selector: 'app-admin-staffs',
  templateUrl: './admin-staffs.component.html',
  styleUrls: ['./admin-staffs.component.css'],
})
export class AdminStaffsComponent implements OnInit {
  // 一些员工数据
  data: StaffDto[] = [];

  // 总计
  total = 0;

  // 是否为加载状态
  loading = true;

  // 页大小
  pageSize = 10;

  // 页索引
  pageIndex = 1;

  // 关键字
  keyword = '';

  // 当前页条目数
  currentPageItems = 0;

  // 抽屉是否显示
  visible = false;

  // 用户表单切换显示 false: 创建、 true: 编辑
  switchStaffFormVisible = false;

  // 编辑的员工
  item: StaffDto;

  constructor(
    private dataService: StaffsService,
    private coreService: CoreService
  ) {}

  ngOnInit(): void {
    this.getDataToTable();
  }

  /**
   * 获取一些数据显示到表格
   */
  getDataToTable() {
    this.loading = true;
    this.dataService
      .find({
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        keyword: this.keyword,
      })
      .subscribe((res) => {
        this.loading = false;
        this.data = res.data;
        this.total = res.total;
        this.currentPageItems = res.data.length;
      });
  }

  /**
   * 查询参数变化
   * @param params 参数
   */
  onQueryParamsChange() {
    this.getDataToTable();
  }

  /**
   * 确认删除员工
   * @param _id _id
   */
  // tslint:disable-next-line: variable-name
  onConfirm(_id: string) {
    this.dataService.deleteById(_id).subscribe(() => {
      const { pageIndex, currentPageItems } = this.coreService.afterDeletingPag(
        this.pageIndex,
        this.currentPageItems
      );
      this.pageIndex = pageIndex;
      this.currentPageItems = currentPageItems;
      this.getDataToTable();
    });
  }

  /**
   * 单击创建员工
   */
  onClickCreateStaffs() {
    this.switchStaffFormVisible = false;
    this.openDrawer();
  }

  /**
   * 单击编辑员工
   * @param item 员工
   */
  // tslint:disable-next-line: variable-name
  onClickEditItem(item: StaffDto) {
    this.item = item;
    this.switchStaffFormVisible = true;
    this.openDrawer();
  }

  /**
   * 打开抽屉
   */
  openDrawer() {
    this.visible = true;
  }

  /**
   * 关闭抽屉
   */
  closeDrawer() {
    this.visible = false;
  }

  /**
   * 更新用户成功
   */
  onUpdate() {
    this.closeDrawer();
    this.getDataToTable();
  }

  /**
   * 创建用户成功
   */
  onCreate() {
    this.closeDrawer();
    this.getDataToTable();
  }
}
